package com.cx.utils.pdf;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
 * @program: rou-yi-api
 * @author: cx
 * @description:将pdf扫描件转换为txt 不要迷恋哥哥只是个传说
 * 以后各种文件的转换都可以参照这个
 *
 * @create: 2025-04-21 14:14
 **/
@Slf4j
@Service
public class PdfToText {

    //获取token
    public static String token() throws EOFException {

        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            JSONObject jsonObjectParam = new JSONObject();
            jsonObjectParam.put("publicKey", "public_key_4aa9c65b4da39be06ec97ee3e2f19393");
            jsonObjectParam.put("secretKey", "secret_key_4bc4b698fe54e706fde8bf854364dbec");
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObjectParam.toString());
            Request request = new Request.Builder()
                    .url("https://api-server.compdf.com/server/v1/oauth/token")
                    .method("POST", body)
                    .build();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            JSONObject jsonObject = JSON.parseObject(responseBody);
            String result = jsonObject.getJSONObject("data").getString("accessToken");
            return result;

        } catch (IOException | JSONException e) {
            throw new EOFException("获取token失败: " + e.getMessage());
        }

    }

    //创建任务
    public static String createTask(String token) throws IOException {
        String result = "";
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 设置连接超时
                .readTimeout(30, TimeUnit.SECONDS)    // 设置读取超时
                .writeTimeout(30, TimeUnit.SECONDS)   // 设置写入超时
                .build();
        try {
            Request request = new Request.Builder()
                    .url("https://api-server.compdf.com/server/v1/task/pdf/txt?language=2")
                    .get()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject jsonObject = JSON.parseObject(responseBody);
                result = jsonObject.getJSONObject("data").getString("taskId");
                System.out.println("方法参数返回" + responseBody.toString());
            } else {
                System.out.println("创建任务失败");
            }
        } catch (Exception e) {
            throw new EOFException("创建任务失败: " + e.getMessage());
        }
        return result;
    }

    //上传文件
    public static void uploadFile(String token, String taskId, MultipartFile file) throws IOException {
        System.out.println("开始上传文件");
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)     // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时时间
                .build();

        try {
            //        MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getOriginalFilename(),
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    file.getBytes()))
                    .addFormDataPart("taskId", taskId)
                    .addFormDataPart("language", "2")
                    .addFormDataPart("parameter", "{\"isAllowOCR\": 1, \"language\": \"chi_sim\"}")
//                    .addFormDataPart("password", "")
                    .build();
            Request request = new Request.Builder()
                    .url("https://api-server.compdf.com/server/v1/file/upload")
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            Response response = client.newCall(request).execute();

            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code  上传文件失败");
            }


        } catch (Exception e) {
            throw new EOFException("上传文件失败: " + e.getMessage());
        }

    }

    //执行任务
    public static void executeTask(String token, String taskId) throws IOException {
        System.out.println("开始执行任务");
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
                    .readTimeout(30, TimeUnit.SECONDS)     // 读取超时时间
                    .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时时间
                    .build();
            Request request = new Request.Builder()
                    .url("https://api-server.compdf.com/server/v1/execute/start?taskId=" + taskId)
                    .get()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            Response response = client.newCall(request).execute();
            System.out.println(response.body().toString());
        } catch (Exception e) {
            throw new EOFException("上传文件失败: " + e.getMessage());
        }

    }

    //查看下载
    public static String fileResult(String token, String taskId) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)     // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时时间
                .build();
        try {

            Request request = new Request.Builder()
                    .url("https://api-server.compdf.com/server/v1/task/taskInfo?taskId=" + taskId)
                    .get()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            Response response = client.newCall(request).execute();

            String result = response.body().string();
            System.out.println(result);
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(result);
                return jsonObject.getJSONObject("data")
                        .getJSONArray("fileInfoDTOList")
                        .getJSONObject(0)
                        .getString("downloadUrl");
            } else {
                return "文件传输失败";
            }
        } catch (Exception e) {
            throw new EOFException("查询结果失败: " + e.getMessage());

        }

    }

    public static MultipartFile urlToMultipartFile2(String fileUrl) throws IOException {
        System.out.println("根据url下载进来了");
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream()) {
            FileItem fileItem = new DiskFileItemFactory()
                    .createItem("file", "text/plain", false, "temp.txt");
            try (OutputStream os = fileItem.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
            CommonsMultipartFile commonsMultipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(commonsMultipartFile.getOriginalFilename());
            return new CommonsMultipartFile(fileItem);
        }
    }

    public static MultipartFile convert(MultipartFile file) throws IOException {
        try {
            String token = "4e028988-9b23-4fbe-bdea-47896ce68a05";
            String taskId = createTask(token);
            uploadFile(token, taskId, file);
            executeTask(token, taskId);
            String fileResult = fileResult(token, taskId);
            int maxRetries = 5; // 最大重试次数
            int retryCount = 0;

            while ((fileResult == null || fileResult.isEmpty()) && retryCount < maxRetries) {
                Thread.sleep(2000); // 休眠 2 秒
                fileResult = fileResult(token, taskId);
                System.out.println("重试次数为" + retryCount + 1);
                retryCount++;
            }

            System.out.println("下载链接为" + fileResult);
            MultipartFile multipartFile = urlToMultipartFile2(fileResult);
            return multipartFile;
        } catch (Exception e) {
            throw new EOFException("业务失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
//        MultipartFile multipartFile = urlToMultipartFile2(" https://pdfreader-dev.oss-cn-shanghai.aliyuncs.com/saas/2025/04/22/937d1fc7a72d42d893aaabacbb1439a2%40test.txt");
//        byte[] bytes = multipartFile.getBytes();
//        System.out.println(new String(bytes, StandardCharsets.UTF_8));


    }

}